package com.tv.enoguia;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap.Config;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.internal.lo;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tv.enoguia.Utils.XMLParser;
import com.tv.enoguia.bean.Celler;
import com.tv.enoguia.database.MySQLiteHelper;

public class HomeActivity extends Activity implements OnTouchListener {

	ImageButton btnList, btnLocation, btnFavour;
	TextView txtList, txtLocation, txtFavour;
	ImageButton btnInfo;
	ViewGroup llInfo;

	private Animation animFadeIn;
	private Animation animFadeOut;

	Button btnClose;
	
	ImageView slideImage;
	ImageView logo;
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false).cacheOnDisc(true)
									.bitmapConfig(Config.ARGB_8888)
									.build();
	
	private int[] IMAGE_IDS = {
			R.drawable.portada01, R.drawable.portada03, R.drawable.portada04,
			R.drawable.portada05, R.drawable.portada06, R.drawable.portada08, R.drawable.portada10, R.drawable.portada14
		};
	
	public int currentimageindex=0;
	Timer timer;
	TimerTask task;
	ImageView slidingimage;
	
	Handler mHandler = new Handler();
	Runnable mUpdateResults = new Runnable() {
        public void run() {
        	
        	AnimateandSlideShow();
        	
        }
    };
	
 // All static variables
 	static final String URL = "http://enoguia.cat/xml_app.php";
 	
 	// XML node keys
 	static final String KEY_CELLERS= "cellers"; // parent node
 	static final String KEY_CELLER = "celler"; // celler 
 	static final String KEY_ID_CELLAR = "id_celler"; // parent node
 	static final String KEY_NAME_CATEGORY = "donom"; // name
 	static final String KEY_TOWN_NAME = "pob"; // townname
 	static final String KEY_CELLAR_NAME = "nom"; // cellar_name
 	static final String KEY_IMAGE_CELLAR = "foto"; // cellar_image
 	
 	static final String KEY_HECT = "hect"; // hecta
 	static final String KEY_AMPOLLER = "ampolles"; // ampollers
 	static final String KEY_LOGO = "logo"; // logo
 	static final String KEY_ADDRESS = "dir"; // address
 	static final String KEY_PHONE = "telefon"; // phone
 	static final String KEY_WEB = "web"; // web
 	static final String KEY_EMAIL = "email"; // email
 	
 	static final String KEY_DES = "desc_en"; // desc_english
 	static final String KEY_DES_CA = "desc_ca"; // desc_catalan
 	static final String KEY_DES_ES = "desc_es"; // desc_english
 	
 	static final String KEY_HORARI = "horari_en"; // horari
 	static final String KEY_HORARI_CA = "horari_ca"; // horari
 	static final String KEY_HORARI_ES = "horari_es"; // horari
 	
 	static final String KEY_PRICES = "preu_en"; // price
 	static final String KEY_PRICES_CA = "preu_ca"; // price
 	static final String KEY_PRICES_ES = "preu_es"; // price
 	
 	static final String KEY_LANGUAGE = "idiomes"; // language
 	static final String KEY_CAPITY_MIN = "capacitat_min"; // capity_min
 	static final String KEY_CAPITY_MAX = "capacitat_max"; // capity_max
 	
 	static final String KEY_VIN = "vins_cata_en"; // vin
 	static final String KEY_VIN_CA = "vins_cata_ca"; // vin
 	static final String KEY_VIN_ES = "vins_cata_es"; // vin
 	
 	static final String KEY_VISIT = "visita_vinyes"; // horari
 	static final String KEY_LON = "lon"; // horari
 	static final String KEY_LAT = "lat"; // horari
 	static final String KEY_LLISTA = "llista_vins"; // lista
 	
 	ArrayList<Celler> cellers = new ArrayList<Celler>();
 	MySQLiteHelper db;
 	ParserAsyntask as;
	


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		btnList = (ImageButton) findViewById(R.id.btn_list);
		btnLocation = (ImageButton) findViewById(R.id.btn_location);
		btnFavour = (ImageButton) findViewById(R.id.btn_favourite);
		
		
		btnInfo = (ImageButton) findViewById(R.id.btn_info);
		
		
		slideImage = (ImageView) findViewById(R.id.slide_image);
		llInfo = (ViewGroup) findViewById(R.id.ll_info);
		btnClose = (Button) findViewById(R.id.btn_close);

		animFadeIn = AnimationUtils.loadAnimation(this, R.anim.anim_fade_in);
		animFadeOut = AnimationUtils.loadAnimation(this, R.anim.anim_fade_out);
		
		logo = (ImageView) findViewById(R.id.logo);
		
		txtList = (TextView) findViewById(R.id.txt_list);
		txtLocation = (TextView) findViewById(R.id.txt_map);
		txtFavour = (TextView) findViewById(R.id.txt_favour);

		init();
		
		printKeyHash(HomeActivity.this);
		
		post();
		
		db = new MySQLiteHelper(this);
		as = new ParserAsyntask();
		as.execute("");
		
		
	}

	void init() {
		btnList.setOnTouchListener(this);
		btnLocation.setOnTouchListener(this);
		btnFavour.setOnTouchListener(this);
		btnInfo.setOnTouchListener(this);
		btnClose.setOnTouchListener(this);
		

		/*if (Locale.getDefault().getISO3Language().equals("eng")){
			
			
		} else if (Locale.getDefault().getISO3Language().equals("cat")) {
			logo.setImageResource(R.drawable.logo_enoguia_ca);
		}else if (Locale.getDefault().getISO3Language().equals("spa")) {
			logo.setImageResource(R.drawable.logo_enoguia_es);
		} else if (Locale.getDefault().getISO3Language().equals("vie")) {
			logo.setImageResource(R.drawable.logo_enoguia_ca);
		}*/
		
		
		String language = Locale.getDefault().getISO3Language().toString(); 
		
		if (language.equals("eng")){
			logo.setImageResource(R.drawable.logo_enoguia_en);
			txtList.setText("Cellars");
			txtLocation.setText("Map");
			txtFavour.setText("Favorites");
		} else if (language.equals("cat")) {
			logo.setImageResource(R.drawable.logo_enoguia_ca);
			txtList.setText("Cellers");
			txtLocation.setText("Mapa");
			txtFavour.setText("Favorits");
		}else if (language.equals("spa")) {
			logo.setImageResource(R.drawable.logo_enoguia_es);
			txtList.setText("Bodegas");
			txtLocation.setText("Mapa");
			txtFavour.setText("Favoritos");
		} else if (language.equals("vie")) {
			logo.setImageResource(R.drawable.logo_enoguia_es);
			txtList.setText("Bodegas");
			txtLocation.setText("Mapa");
			txtFavour.setText("Favorits");
		}
		
	}
	
	

	@Override
	protected void onPause() {
		super.onPause();
		Log.i("DATA", "PAUSE--------");
		if (timer != null){
			timer.cancel();
		}
		animFadeIn.cancel();
		animFadeOut.cancel();
		mHandler.removeCallbacks(mUpdateResults);
		mHandler.removeCallbacks(task);
		mHandler.removeCallbacksAndMessages(null);
	}
	
	void post(){
		int delay = 500; // delay for 1 sec.

        int period = 4000; // repeat every 4 sec.

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {

        	 mHandler.post(mUpdateResults);

        }

        }, delay, period);
	}
	

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_list:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				gotoMainTab("0");
			}
			break;

		case R.id.btn_location:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				gotoMainTab("1");
			}
			break;
		case R.id.btn_favourite:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				gotoMainTab("2");
			}
			break;
		case R.id.btn_info:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if(llInfo.getVisibility() == View.VISIBLE){
					llInfo.startAnimation(animFadeOut);
					llInfo.setVisibility(View.INVISIBLE);
				} else {
					llInfo.startAnimation(animFadeIn);
					llInfo.setVisibility(View.VISIBLE);
				}
				
			}
			break;
		case R.id.btn_close:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				llInfo.startAnimation(animFadeOut);
				llInfo.setVisibility(View.INVISIBLE);
			}
			break;
		}
		return false;
	}

	void gotoMainTab(String i) {
		Intent t = new Intent(HomeActivity.this, MainPanelActivity.class);
		t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		t.putExtra("value", i);
		startActivity(t);
	}
	
	 public void onClick() {
	        android.os.Process.killProcess(android.os.Process.myPid());
	  }
	
	 private void AnimateandSlideShow() {
	    	
	    	
//    	slideImage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
   		
    	ImageLoader.getInstance().displayImage("drawable://"+IMAGE_IDS[currentimageindex%IMAGE_IDS.length], slideImage, options);
    	
    	currentimageindex++;
    	
   		Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.anim_fade_in);
   		slideImage.startAnimation(rotateimage);
	    }
	 
	 
	 void parser(){
		 
		 	/*btnList.setEnabled(false);
			btnLocation.setEnabled(false);
			btnFavour.setEnabled(false);*/
			
			ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

			XMLParser parser = new XMLParser();
			try {
				String xml = parser.getXmlFromUrl(URL); // getting XML
				Document doc = parser.getDomElement(xml); // getting DOM element	
				NodeList nl = doc.getElementsByTagName(KEY_CELLER);
				// xoa
//				db.deteleAllRecord();
				
				// looping through all item nodes <item>
				for (int i = 0; i < nl.getLength(); i++) {
					
					Celler celler = new Celler();
					// creating new HashMap
					HashMap<String, String> map = new HashMap<String, String>();
					Element e = (Element) nl.item(i);
					// adding each child node to HashMap key => value
//					map.put(KEY_CELLER, parser.getValue(e, KEY_CELLER));
					
					map.put(KEY_NAME_CATEGORY, parser.getValue(e, KEY_NAME_CATEGORY));
					map.put(KEY_TOWN_NAME, parser.getValue(e, KEY_TOWN_NAME));
					map.put(KEY_CELLAR_NAME, parser.getValue(e, KEY_CELLAR_NAME));
					map.put(KEY_IMAGE_CELLAR, parser.getValue(e, KEY_IMAGE_CELLAR));
					
					celler.setId(parser.getValue(e, KEY_ID_CELLAR));
					celler.setNameCategory(parser.getValue(e, KEY_NAME_CATEGORY));
					celler.setTowName(parser.getValue(e, KEY_TOWN_NAME));
					celler.setCellarName(parser.getValue(e, KEY_CELLAR_NAME));
					celler.setPhoto(parser.getValue(e, KEY_IMAGE_CELLAR));
					celler.setHect(parser.getValue(e, KEY_HECT));
					celler.setAmpoller(parser.getValue(e, KEY_AMPOLLER));
					celler.setLogo(parser.getValue(e, KEY_LOGO));
					celler.setAddress(parser.getValue(e, KEY_ADDRESS));
					celler.setPhone(parser.getValue(e, KEY_PHONE));
					celler.setWeb(parser.getValue(e, KEY_WEB));
					celler.setEmail(parser.getValue(e, KEY_EMAIL));
					
					celler.setDesCriptionE(parser.getValue(e, KEY_DES));
					celler.setDesCriptionCA(parser.getValue(e, KEY_DES_CA));
					celler.setDesCriptionES(parser.getValue(e, KEY_DES_ES));
					
					celler.setHorariE(parser.getValue(e, KEY_HORARI));
					celler.setHorariCA(parser.getValue(e, KEY_HORARI_CA));
					celler.setHorariES(parser.getValue(e, KEY_HORARI_ES));
					
					celler.setPriceE(parser.getValue(e, KEY_PRICES));
					celler.setPriceCA(parser.getValue(e, KEY_PRICES_CA));
					celler.setPriceES(parser.getValue(e, KEY_PRICES_ES));
					
					celler.setLanguageE(parser.getValue(e, KEY_LANGUAGE));
					celler.setCapityMin(parser.getValue(e, KEY_CAPITY_MIN));
					celler.setCapityMax(parser.getValue(e, KEY_CAPITY_MAX));
					
					celler.setVinE(parser.getValue(e, KEY_VIN));
					celler.setVinCA(parser.getValue(e, KEY_VIN_CA));
					celler.setVinES(parser.getValue(e, KEY_VIN_ES));
					
					celler.setVisitYes(parser.getValue(e, KEY_VISIT));
					celler.setLon(parser.getValue(e, KEY_LON));
					celler.setLat(parser.getValue(e, KEY_LAT));
//					celler.setLiked(0);
					celler.setListtaVins(parser.getValue(e, KEY_LLISTA));
					
					
					
					cellers.add(celler);
					
					db.insertCeller(celler);
					// adding HashList to ArrayList
					menuItems.add(map);
					
				}
				Log.i("DATA", cellers.get(0).getAddress());
				/*for (int i = 0; i < cellers.size(); i++){
					Log.i("DATA", cellers.get(i).toString());
				}*/
				
				as.cancel(true);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			

			
		
		}
		
		private class ParserAsyntask extends AsyncTask<String, String, String>{

			@Override
			protected String doInBackground(String... params) {
				parser();
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				btnList.setEnabled(true);
				btnLocation.setEnabled(true);
				btnFavour.setEnabled(true);
			}
		}
		
		public static String printKeyHash(Activity context) {
			PackageInfo packageInfo;
			String key = null;
			try {

				//getting application package name, as defined in manifest
				String packageName = context.getApplicationContext().getPackageName();

				//Retriving package info
				packageInfo = context.getPackageManager().getPackageInfo(packageName,
						PackageManager.GET_SIGNATURES);
				
				Log.e("Package Name=", context.getApplicationContext().getPackageName());
				
				for (Signature signature : packageInfo.signatures) {
					MessageDigest md = MessageDigest.getInstance("SHA");
					md.update(signature.toByteArray());
					key = new String(Base64.encode(md.digest(), 0));
				
					// String key = new String(Base64.encodeBytes(md.digest()));
					Log.e("Key Hash=", key);

				}
			} catch (NameNotFoundException e1) {
				Log.e("Name not found", e1.toString());
			}

			catch (NoSuchAlgorithmException e) {
				Log.e("No such an algorithm", e.toString());
			} catch (Exception e) {
				Log.e("Exception", e.toString());
			}

			return key;
		}
	 
}
